<template>
  <div>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      ref="crud"
      v-model="form"
      :page.sync="page"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      @row-del="rowDel"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-upload
          :auto-upload="false"
          :show-file-list="false"
          action="action"
          :on-change="handleChange"
        >
          <el-button size="small" type="primary">导入 excel</el-button>
        </el-upload>
      </template>

      <template slot="menu" slot-scope="{row,size}">
        <el-button :size="size" type="text" icon="el-icon-view" @click="preview(row)">证书预览</el-button>
      </template>
      <template slot="imageUrlForm">
        <a :href="form.imageUrl" target="__blank" alt>{{form.imageUrl}}</a>
      </template>
    </avue-crud>
    <el-dialog title="预览" :visible.sync="dialogVisible" width="800px" top="1vh">
      <div class="preview">
        <div class="imgBox" ref="imgBoxRef">
          <span>{{currentRow.name}}</span>
          <span>{{currentRow.sex}}</span>
          <span>{{currentRow.id}}</span>
          <span>{{currentRow.type}}</span>
          <span>{{currentRow.score}}</span>
          <span>{{currentRow.sexIndex}}</span>
          <span>{{currentRow.speed}}</span>
          <span>{{currentRow.allIndex}}</span>
        </div>
        <div class="btnBox">
          <el-button type="primary" size="small" icon="el-icon-download" @click="downloadImg">保存图片</el-button>
          <el-button type="primary" size="small" icon="el-icon-upload" @click="uploadImg">上传图片</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, save, update, remove, importData } from "@/api/homeView";
import html2canvas from "html2canvas";
export default {
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      option: {
        maxHeight: 800,
        indexLabel: "序号",
        title: "尖山马拉松",
        tip: false, // 提示
        align: "center",
        menuAlign: "center", //
        index: true,
        viewBtn: true,
        menuWidth: 350,
        searchMenuSpan: 5, // 搜索所占宽比例  24是整行
        border: true, // 边
        excelBtn: false, // 导入按钮
        selection: false, // 选择/反选
        dialogClickModal: false, // 遮罩层点击是否可关闭  true/false（关闭/否）
        columnBtn: false,
        labelWidth: 120,
        excelBtn: true,
        column: [
          {
            label: "姓名",
            search: true,
            searchSpan: 4.8,
            prop: "name",
            editDisabled: true,
            rules: [
              // 校验
              {
                required: true,
                message: "请输入姓名",
                trigger: "blur"
              },
              {
                max: 6,
                type: "string",
                message: "长度6字符以内"
              }
            ]
          },
          {
            label: "性别",
            type: "select",
            value: "男",
            prop: "sex",
            search: true,
            searchSpan: 4.8,
            dicData: [
              {
                label: "男",
                value: "男"
              },
              {
                label: "女",
                value: "女"
              }
            ]
          },
          {
            label: "参赛号",
            search: true,
            searchSpan: 4.8,
            prop: "id",
            editDisabled: true,
            rules: [
              // 校验
              {
                required: true,
                message: "请输入参赛号",
                trigger: "blur"
              }
            ]
          },
          {
            label: "参赛项目",
            prop: "type",
            value: "欢乐跑",
            type: "select",
            search: true,
            searchSpan: 4.8,
            dicData: [
              {
                label: "半马",
                value: "半马"
              },
              {
                label: "欢乐跑",
                value: "欢乐跑"
              }
            ],
            rules: [
              {
                required: true,
                message: "请选择参赛项目",
                trigger: "blur"
              }
            ]
          },
          {
            label: "完赛成绩",
            prop: "score",
            rules: [
              {
                required: true,
                message: "请输入完赛成绩",
                trigger: "blur"
              }
            ]
          },
          {
            label: "平均配速",
            prop: "speed",
            rules: [
              {
                required: true,
                message: "请输入平均配速",
                trigger: "blur"
              }
            ]
          },
          {
            label: "在线证书",
            prop: "imageUrl",
            listType: "picture-card",
            accept: "image/jpeg,image/png",
            span: 24,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: true,
            formslot: true,
            formatter(row) {
              return row.imageUrl ? "有" : "无";
            }
          },
          {
            label: "性别排名",
            prop: "sexIndex",
            type: "number"
            // display: false
          },
          {
            label: "全部选手排名",
            prop: "allIndex",
            type: "number"
            // display: false
          }
        ]
      },
      data: [],
      dialogVisible: false,
      currentRow: {}
    };
  },
  computed: {},
  mounted() {},
  methods: {
    rowSave(row, done, loading) {
      save(row).then(
        res => {
          if (!res.success) {
            this.$message.error(res.msg);
            return loading();
          }
          this.$message.success("新增成功");
          this.onLoad();
          done();
        },
        errRes => {
          this.$message.error(errRes.msg);
          return loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        res => {
          if (!res.success) {
            this.$message.error(res.msg);
            return loading();
          }
          this.$message.success("编辑成功");
          this.onLoad();
          done();
        },
        errRes => {
          this.$message.error(errRes.msg);
          return loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        type: "warning"
      }).then(
        () => {
          remove(row.id).then(
            res => {
              if (!res.success) {
                return this.$message.error(res.msg);
              }
              this.$message.success("删除成功");
              this.onLoad();
            },
            errRes => {
              return this.$message.error(errRes.msg);
            }
          );
        },
        () => {}
      );
    },
    beforeOpen(done, type) {
      // if (["edit", "view"].includes(type)) {
      //   getDetail(this.form.id).then(res => {
      //     this.form = res.data.data;
      //   });
      // }
      done();
    },
    beforeClose(done) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(this.query).then(res => {
        console.log("getList", res);
        this.loading = false;
        this.data = res.data;
      });
    },
    preview(row) {
      console.log(row);
      this.dialogVisible = true;
      this.currentRow = row;
    },
    uploadImg() {
      const demoElement = this.$refs.imgBoxRef;
      html2canvas(demoElement)
        .then(canvas => {
          canvas.toBlob(blob => {
            const formData = new FormData();
            console.log(blob);
            formData.append("file", blob, this.currentRow.id + ".png"); // 'screenshot.png' 是上传的文件名
            fetch("http://175.6.40.69:8245/uploadfile", {
              method: "POST",
              body: formData
            })
              .then(response => response.json())
              .then(res => {
                console.log("Upload success:", res);
                if (res.code !== 200) this.$message.success("上传文件失败");
                const params = {
                  ...this.currentRow,
                  imageUrl:
                    "http://175.6.40.69:8245/get_file_by_name/?file_name=" +
                    res.file_name
                };
                update(params).then(
                  res => {
                    if (!res.success) {
                      return this.$message.error(res.msg);
                    }
                    this.$message.success("上传文件成功");
                    this.dialogVisible = false;
                    this.onLoad();
                  },
                  errRes => {
                    return this.$message.error(errRes.msg);
                  }
                );
              })
              .catch(error => {
                console.error("Upload error:", error);
              });
          }, "image/png");
        })
        .catch(error => {
          // 处理截图错误
          console.error("Capture error:", error);
        });
    },
    downloadImg() {
      const demoElement = this.$refs.imgBoxRef;
      html2canvas(demoElement).then(canvas => {
        const url = canvas.toDataURL("image/png");
        const a = document.createElement("a");
        a.href = url;
        a.download = this.currentRow.id + ".png";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        this.dialogVisible = false;
      });
    },
    handleChange(file, fileLis) {
      this.$Export.xlsx(file.raw).then(data => {
        console.log(data);
        const newData = data.results.map(item => {
          const obj = {};
          data.header.forEach(item1 => {
            const row = this.option.column.find(item2 => item2.label === item1);
            if (row) {
              if (row.prop === "score") {
                obj[row.prop] = this.timeFromDecimalH(item[item1]);
              } else if (row.prop === "speed") {
                obj[row.prop] = this.timeFromDecimalM(item[item1]);
              } else {
                obj[row.prop] = item[item1];
              }
            }
          });
          return obj;
        });
        console.log(newData);
        importData(newData).then(
          res => {
            if (!res.success) {
              return this.$message.error(res.msg);
            }
            this.$message.success("excel导入成功");
            this.onLoad();
          },
          errRes => {
            return this.$message.error(errRes.msg);
          }
        );
      });
    },
    timeFromDecimalH(decimalTime) {
      // 一天有86400秒
      const totalSeconds = (decimalTime * 86400).toFixed(0);
      // 计算小时数（取整）
      const hours = Math.floor(totalSeconds / 3600);
      console.log(hours);
      // 计算剩余的分钟数（先减去小时数所占的秒数）
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      // 计算剩余的秒数
      const seconds = totalSeconds % 60;
      return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(
        2,
        "0"
      )}:${String(seconds).padStart(2, "0")}`;
    },
    timeFromDecimalM(decimalTime) {
      // 一天有86400秒
      const totalSeconds = (decimalTime * 86400).toFixed(0);
      // 计算小时数（取整）
      const hours = Math.floor(totalSeconds / 3600);
      console.log(hours);
      // 计算剩余的分钟数（先减去小时数所占的秒数）
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      // 计算剩余的秒数
      const seconds = totalSeconds % 60;
      return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(
        2,
        "0"
      )}`;
    }
  }
};
</script>

<style lang="scss" scoped>
.preview {
  width: 100%;
  text-align: center;
  .imgBox {
    display: inline-block;
    // width: 707px;
    // height: 1000px;
    width: 565px;
    height: 800px;
    background: url(../assets/images/template.png) no-repeat;
    background-size: 100% 100%;
    position: relative;
    & > span {
      position: absolute;
      color: #000;
      font-weight: 800;
      width: 6em;
      height: 1em;
      font-size: 16px;
    }
    & > span:nth-child(1) {
      top: 41.5%;
      left: 30%;
    }
    & > span:nth-child(2) {
      top: 41.5%;
      left: 70%;
    }
    & > span:nth-child(3) {
      top: 49.5%;
      left: 30%;
    }
    & > span:nth-child(4) {
      top: 49.5%;
      left: 70%;
    }
    & > span:nth-child(5) {
      top: 57%;
      left: 30%;
    }
    & > span:nth-child(6) {
      top: 57%;
      left: 70%;
    }
    & > span:nth-child(7) {
      top: 65%;
      left: 30%;
    }
    & > span:nth-child(8) {
      top: 65%;
      left: 76%;
      width: 4em;
    }
  }
}
.btnBox {
  padding-top: 20px;
}

::v-deep .avue-crud__header .avue-crud__left > div {
  display: inline-block;
}
</style>